package com.cdream.basic.algorithm.leetcode.findElement;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author cdream
 * @date 5/22/21
 */
public class Question15 {
    List<List<Integer>> res = new ArrayList<>();

    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 2; i++) {
            if (nums[i] > 0) {
                break;
            }
            // 相同则跳过
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            int l = i + 1;
            int r = nums.length - 1;

            while (l < r) {
                int sum = nums[i] + nums[l] + nums[r];
                if (sum == 0) {
                    List<Integer> integers = new ArrayList<>();
                    integers.add(i);
                    integers.add(l);
                    integers.add(r);
                    res.add(integers);
                    while (l < r && nums[l] == nums[++l]) {
                    }
                    while (l < r && nums[r] == nums[--r]) {
                    }
                } else if (sum > 0) {
                    while (l < r && nums[r] == nums[--r]) {
                    }
                } else {
                    while (l < r && nums[l] == nums[++l]) {
                    }
                }
            }
        }
        return res;
    }
}
